import type { Dict, DictData, DictDataDTO } from './data'
import type { DictDTO } from './data'
import { useDefaultRef } from '@/hooks/useDefaultRef'
import { defineStore } from 'pinia'
import { ref, shallowRef } from 'vue'
import { deleteDict, deleteDictData, getDictData, getDicts, putDict, putDictData } from './service'
import { ElMessageBox } from 'element-plus'

export const useDictStore = defineStore('dict', () => {
  const records = shallowRef<Dict[]>([])

  const [current, _resetCurrent] = useDefaultRef(() => 1)

  const total = ref(0)

  const [search, _resetSearch] = useDefaultRef(() => ({
    dictName: '',
    dictType: '',
  }))

  const onGet = async () => {
    const data = await getDicts({ current: current.value })
    records.value = data.records
  }

  const selection = ref<Dict[]>([])

  const onDelete = async (row: Dict) => {
    try {
      await ElMessageBox.confirm(`确定删除该字典: ${row.dictType} ？`, {
        title: '删除字典',
        type: 'error',
      })
      await deleteDict([row.id])
      records.value = records.value.filter(({ id }) => id !== row.id)
    } catch {
      console.log(`取消删除`)
    }
  }

  const onBatchDelete = async () => {
    try {
      if (selection.value.length > 0) {
        const msg = selection.value.map(({ dictType }) => dictType).join('，')
        await ElMessageBox.confirm(`以下字典将被删除：${msg}，确认删除？`, {
          title: '批量删除',
          type: 'error',
        })
        await deleteDict(selection.value.map(({ id }) => id))
        records.value = records.value.filter((item) => !selection.value.some(({ id }) => item.id === id))
      }
    } catch {
      console.log(`取消删除`)
    }
  }

  const onSearch = async () => {
    _resetCurrent()
    const dto: DictDTO.Get = { current: current.value }
    if (search.value.dictName.trim()) dto.dictName = search.value.dictName
    if (search.value.dictType.trim()) dto.dictType = search.value.dictType
    const data = await getDicts(dto)
    records.value = data.records
  }

  const onResetSearch = () => {
    _resetSearch()
    _resetCurrent()
    onGet()
  }

  const [form, onResetForm] = useDefaultRef<{
    on: boolean
    id: DictDTO.Put['id']
    items: Pick<DictDTO.Put, 'dictName' | 'dictType' | 'description'>
  }>(() => ({
    on: false,
    id: void 0,
    items: {
      dictName: '',
      dictType: '',
      description: '',
    },
  }))

  const onStartUpdate = (dto?: Pick<DictDTO.Put, 'id' | 'dictName' | 'dictType' | 'description'>) => {
    if (dto) form.value = { ...form.value, ...dto }
    form.value.on = true
  }

  const onSubmitUpdate = async () => {
    const dto: DictDTO.Put = form.value.items
    if (form.value.id) dto.id = form.value.id
    await putDict(dto)
    await onGet()
    onResetForm()
  }

  return {
    records,
    current,
    total,
    search,
    onGet,
    selection,
    onDelete,
    onBatchDelete,
    onSearch,
    onResetSearch,
    form,
    onResetForm,
    onStartUpdate,
    onSubmitUpdate,
  }
})

export const useDictDataStore = defineStore('dict-data', () => {
  const drawerOn = ref(false)

  const dictType = ref('')

  const records = shallowRef<DictData[]>([])

  const total = ref(0)

  const onReset = () => {
    drawerOn.value = false
    dictType.value = ''
    records.value = []
    total.value = 0
  }

  const onGet = async () => {
    if (!dictType.value) return
    const data = await getDictData({ dictType: dictType.value })
    records.value = data.records
    total.value = data.total
  }

  const onDelete = async (row: DictData) => {
    try {
      await ElMessageBox.confirm(`确定删除该字典数据？: ${row.itemValue} ？`, {
        title: '删除字典值',
        type: 'error',
      })
      const success = await deleteDictData([row.id])
      if (success) records.value = records.value.filter(({ id }) => id !== row.id)
    } catch {
      console.warn(`取消删除`)
    }
  }

  const selection = ref<DictData[]>([])

  const onBatchDelete = async () => {
    if (selection.value.length <= 0) return
    if (!dictType.value) return
    try {
      await ElMessageBox.confirm(
        `确定以下该字典数据？: ${selection.value.map(({ itemValue }) => itemValue).join('，')} ？`,
        {
          title: '删除字典值',
          type: 'error',
        }
      )
      const success = await deleteDictData(selection.value.map(({ id }) => id))
      if (success) records.value = records.value.filter(({ id }) => !selection.value.some((item) => item.id === id))
    } catch {
      console.warn(`取消删除`)
    }
  }

  const [form, onResetForm] = useDefaultRef<{
    on: boolean
    id: DictData['id'] | undefined
    items: Pick<DictData, 'status' | 'itemLabel' | 'itemValue' | 'description'>
  }>(() => ({
    on: false,
    id: void 0,
    items: {
      status: 1,
      description: '',
      itemLabel: '',
      itemValue: '',
    },
  }))

  const onStartConfig = async (row: Dict) => {
    dictType.value = row.dictType
    await onGet()
    drawerOn.value = true
  }

  const onStartUpdate = async (row?: DictData) => {
    if (row) {
      const { status, description, itemLabel, itemValue } = row
      form.value.items = { status, description, itemLabel, itemValue }
      if (row.id) form.value.id = row.id
    }
    form.value.on = true
  }

  const onSubmitUpdate = async () => {
    const dto: DictDataDTO.Put = { dictType: dictType.value, ...form.value.items }
    if (form.value.id) dto.id = form.value.id
    await putDictData(dto)
    await onGet()
    onResetForm()
  }

  return {
    drawerOn,
    dictType,
    records,
    total,
    onReset,
    onGet,
    onDelete,
    selection,
    onBatchDelete,
    form,
    onResetForm,
    onStartConfig,
    onStartUpdate,
    onSubmitUpdate,
  }
})
